import 'package:dio/dio.dart';

typedef Success = void Function(dynamic data);
typedef Error = void Function(Exception e);
typedef Start = void Function(HttpRequest request);
typedef Finished = void Function(HttpRequest request);

enum HttpMethod { GET, POST }

class HttpRequest {
  String url;
  Map<String, dynamic> params;
  String body;
  Map<String, String> header;
  HttpMethod method;
  Success success;
  Error error;
  Start start;
  Finished finished;

  HttpRequest(this.url,
      {this.params,
        this.body,
        this.header,
        this.method,
        this.success,
        this.error,
        this.start,
        this.finished});
}

abstract class IHttp {
  void get(HttpRequest request);

  void post(HttpRequest request);
}

class DioHttp implements IHttp {
  @override
  void get(HttpRequest request) async {
    try {
      Response response =
          await Dio().get(request.url, queryParameters: request.params);
      print(response.data);
      if (request.success != null) {
        request.success(response.data);
      }
    } catch (e) {
      print(e);
      if (request.error != null) {
        request.error(e);
      }
    }
  }

  @override
  void post(HttpRequest request) async {
    try {
      Response response = await Dio().post(
          request.url, queryParameters: request.params);
      print(response.data);
      if (request.success != null) {
        request.success(response.data);
      }
    } catch (e) {
      print(e);
      if (request.error != null) {
        request.error(e);
      }
    }
  }
}

class Http {
  static IHttp http = DioHttp();

  static void get(HttpRequest request) {
    http.get(request);
  }

  static void post(HttpRequest request) {
    http.post(request);
  }
}
